using System;
using Microsoft.Win32;

namespace svs.Mobile.BeyondMedia.Objects
{
	internal class LicenseManager
	{
		private static string m_Version;
		private static string APP_REGISTRY_ROOT = Registry.CurrentUser + @"\SOFTWARE\BeyondPod";
		private static DateTime m_Expiration;
		private static string m_DeviceID;
		private static bool m_Tagged;
		
		private static int DAYS_TO_EXPIRE = 100;
		private static string ENCRYPTION_KEY = "BeyondPod";
		const string LICENSE_SETTINGS_KEY = "Settings";

		static LicenseManager()
		{
			m_Tagged = LoadData();

			if (!m_Tagged)
			{
				m_Version = Configuration.ProductVersion;
				m_Expiration = DateTime.Now.AddDays(DAYS_TO_EXPIRE);
				m_DeviceID = "GNR";

				try
				{
					SaveData();
				}
				catch (Exception ex)
				{
					Helpers.WriteLogEntry("Unable to save license data!. Reason:" + ex.Message);
				}
			}
		}

		private static string ProductVersion
		{
			get { return m_Version; }
		}

		private static DateTime Expiration
		{
			get { return m_Expiration; }
		}

		private  static string DeviceID
		{
			get { return m_DeviceID; }
		}

		private static bool LoadData()
		{
			string value = Registry.GetValue(APP_REGISTRY_ROOT, LICENSE_SETTINGS_KEY, "") as String;

			if (value == null)
				return false;

			value = Decrypt(value);

			if (value.Length == 0)
				return false;

			char[] dels = {','};

			string[] parts = value.Split(dels);

			if (parts.Length != 3)
				return false;

			try
			{
				m_Version = parts[0];
				m_Expiration = DateTime.Parse(parts[1]);
				m_DeviceID = parts[2];
			}
			catch 
			{
				Helpers.WriteLogEntry("Unable to load the license data");
				return false;
			}

			return true;
		}

		private static void SaveData()
		{
			string value = string.Format("{0}|{1}|{2}", m_Version, m_Expiration.ToShortDateString(), m_DeviceID);
			Registry.SetValue(APP_REGISTRY_ROOT, LICENSE_SETTINGS_KEY, Encrypt(value), RegistryValueKind.String);
		}

		private static bool IsExpired()
		{
			return m_Expiration < DateTime.Now;
		}

		#region Encryption/Decryption

		private static string Encrypt(string i_value)
		{
			try
			{
				return new XTea().EncryptString(i_value, ENCRYPTION_KEY);
			}
			catch
			{
				Helpers.WriteLogEntry("Unable to encrypt the license key!");
				return null;
			}
		}

		private static string Decrypt(string i_value)
		{
			try
			{
				return new XTea().Decrypt(i_value, ENCRYPTION_KEY);
			}
			catch
			{
				Helpers.WriteLogEntry("Unable to decrypt the license key!");
				return String.Empty;
			}
		}

		#endregion
	}
}